<template>
  <view class="product-detail">
    <!-- 商品图片轮播 -->
    <swiper class="product-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
      <swiper-item v-for="(url, index) in imageUrls" :key="index">
        <image :src="url" mode="aspectFill" class="swiper-image" @error="handleImageError"></image>
      </swiper-item>
    </swiper>

    <!-- 商品基本信息 -->
    <view class="product-info">
      <view class="price-section">
        <text class="points-price">{{ product.pointsPrice }} 积分</text>
        <text class="original-price" v-if="product.originalPrice">原价: ¥{{ product.originalPrice }}</text>
      </view>
      <view class="title-section">
        <text class="product-name">{{ product.productName }}</text>
      </view>
      <view class="user-points-section">
        <text class="user-points-label">我的积分：</text>
        <text class="user-points-value">{{ userPoints }}</text>
      </view>
    </view>

    <!-- 商品详细信息 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <view class="detail-content">
        <view class="detail-item">
          <text class="label">商品品牌</text>
          <text class="value">{{ product.productBrand }}</text>
        </view>
        <view class="detail-item">
          <text class="label">限兑数量</text>
          <text class="value">{{ product.exchangeLimit }}</text>
        </view>
        <view class="detail-item">
          <text class="label">商品类型</text>
          <text class="value">{{ getDictLabel(productTypeOptions, product.productCategory) }}</text>
        </view>
        <view class="detail-item">
          <text class="label">商品状态</text>
          <text class="value">{{ getDictLabel(productStatusOptions, product.productStatus) }}</text>
        </view>
      </view>
    </view>

    <!-- 商品描述 -->
    <view class="description-section">
      <view class="section-title">商品描述</view>
      <view class="description-content">
        <text>{{ product.productDescription || '暂无描述' }}</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="quantity-section">
        <text class="quantity-label">数量：</text>
        <view class="quantity-control">
          <button class="quantity-btn" @click="decreaseQuantity" :disabled="exchangeQuantity <= 1">-</button>
          <text class="quantity-value">{{ exchangeQuantity }}</text>
          <button class="quantity-btn" @click="increaseQuantity" :disabled="exchangeQuantity >= maxQuantity">+</button>
        </view>
      </view>
      <button class="exchange-btn" @click="handleExchange">立即兑换</button>
    </view>
  </view>
</template>

<script setup>
import config from "@/config"
import { getProduct } from "@/api/product/product";
import { exchangeProduct } from "@/api/pointRecord/pointRecord";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import { getDicts } from "@/api/system/dict/data";
import useUserStore from '@/store/modules/user';
import request from '@/utils/request';

// 字典数据
const productTypeOptions = ref([]); // 商品类型字典
const productStatusOptions = ref([]); // 商品状态字典

// 表单参数
const product = ref({
  id: null,
  productCode: null,
  productName: null,
  productDescription: null,
  productImage: "",
  pointsPrice: null,
  originalPrice: null,
  stockQuantity: null,
  soldQuantity: null,
  productCategory: null,
  productBrand: null,
  sortOrder: null,
  exchangeLimit: null,
  startTime: null,
  endTime: null,
  productStatus: null
});

// 处理图片URL
const imageUrls = computed(() => {
  if (!product.value.productImage) return [];
  const urls = product.value.productImage.split(',').filter(url => url);
  return urls.map(url => {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    }
    return config.baseUrl + url;
  });
});

// 获取字典数据
const getDictData = () => {
  getDicts('product_type').then(response => {
    if (response.code === 200) {
      productTypeOptions.value = response.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
    }
  });
  getDicts('product_status').then(response => {
    if (response.code === 200) {
      productStatusOptions.value = response.data.map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }));
    }
  });
};

// 根据字典value获取label
const getDictLabel = (options, value) => {
  if (!value || !options || !options.length) return value;
  const option = options.find(item => String(item.value) === String(value));
  return option ? option.label : value;
};

// 获取商品详情
const getProductDetail = (id) => {
  if (!id) {
    uni.showToast({
      title: '商品ID不能为空',
      icon: 'none'
    });
    return;
  }

  getProduct(id).then(res => {
    if (res.code === 200) {
      product.value = res.data;
    } else {
      uni.showToast({
        title: res.msg || '获取商品详情失败',
        icon: 'none',
        duration: 3000
      });
    }
  }).catch(error => {
    console.error('获取商品详情失败:', error);
    uni.showToast({
      title: '获取商品详情失败',
      icon: 'none',
      duration: 3000
    });
  });
};

// 页面加载
onLoad((options) => {
  getDictData();
  userStore.getInfo().then(() => {
    if (options && options.id) {
      getProductDetail(options.id);
    }
  });
});

// 页面显示
onShow(() => {
  userStore.getInfo().then(() => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    if (currentPage.options && currentPage.options.id) {
      getProductDetail(currentPage.options.id);
    }
  });
});

// 处理图片加载错误
const handleImageError = (e) => {
  e.target.src = '/static/images/default.png';
};

// 处理兑换
function handleExchange() {
  // 检查商品状态
  if (product.value.productStatus === 2) {
    uni.showToast({
      title: '商品已下架',
      icon: 'none'
    });
    return;
  }

  // 检查库存
  if (!product.value.stockQuantity || product.value.stockQuantity <= 0) {
    uni.showToast({
      title: '商品库存不足',
      icon: 'none'
    });
    return;
  }

  // 检查兑换数量是否超过库存
  if (exchangeQuantity.value > product.value.stockQuantity) {
    uni.showToast({
      title: '兑换数量超过库存',
      icon: 'none'
    });
    return;
  }

  // 检查兑换数量是否超过限兑数量
  if (product.value.exchangeLimit && exchangeQuantity.value > product.value.exchangeLimit) {
    uni.showToast({
      title: `最多只能兑换 ${product.value.exchangeLimit} 件`,
      icon: 'none'
    });
    return;
  }

  // 检查用户积分是否足够
  const requiredPoints = product.value.pointsPrice * exchangeQuantity.value;
  if (userPoints.value < requiredPoints) {
    uni.showModal({
      title: '积分不足',
      content: `当前积分：${userPoints.value}，需要积分：${requiredPoints}，积分不足无法兑换`,
      showCancel: false,
      confirmText: '我知道了'
    });
    return;
  }

  // 检查是否在销售时间范围内
  const now = new Date().getTime();
  const startTime = new Date(product.value.startTime).getTime();
  const endTime = new Date(product.value.endTime).getTime();

  if (now < startTime) {
    uni.showToast({
      title: '商品未开始销售',
      icon: 'none'
    });
    return;
  }

  if (now > endTime) {
    uni.showToast({
      title: '商品已结束销售',
      icon: 'none'
    });
    return;
  }

  // 显示确认对话框
  uni.showModal({
    title: '确认兑换',
    content: `确定要使用 ${product.value.pointsPrice * exchangeQuantity.value} 积分兑换 ${exchangeQuantity.value} 件该商品吗？`,
    success: (res) => {
      if (res.confirm) {
        // 兑换前刷新用户信息
        userStore.getInfo().then(() => {
          // 调用兑换API
          const exchangeData = {
            productId: product.value.id,
            productName: product.value.productName,
            pointsPrice: product.value.pointsPrice,
            exchangeQuantity: exchangeQuantity.value,
            userId: userStore.userId // 使用getter获取用户ID
          };
          
          uni.showLoading({
            title: '兑换中...'
          });
          
          // 使用封装的request工具
          request({
            url: '/pointRecord/pointRecord/exchange',
            method: 'POST',
            data: exchangeData
          }).then(res => {
            uni.hideLoading();
            
            if (res.code === 200) {
              uni.showToast({
                title: res.msg || '兑换成功',
                icon: 'success'
              });
              // 兑换成功后强制刷新用户信息和用户积分
              userStore.getInfo().then(() => {
                getProductDetail(product.value.id);
              });
            } else {
              // 直接显示后端返回的错误消息
              uni.showToast({
                title: res.msg || '兑换失败',
                icon: 'none',
                duration: 3000
              });
            }
          }).catch(error => {
            uni.hideLoading();
            console.error('兑换失败:', error);
            uni.showToast({
              title: '兑换失败，请稍后重试',
              icon: 'none',
              duration: 3000
            });
          });
        });
      }
    }
  });
}

// 兑换数量
const exchangeQuantity = ref(1);
const maxQuantity = computed(() => product.value.exchangeLimit);

// 用户积分信息，使用store的getter
const userStore = useUserStore();
const userPoints = computed(() => userStore.currentPoints);

// 增加兑换数量
function increaseQuantity() {
  if (exchangeQuantity.value < maxQuantity.value) {
    exchangeQuantity.value++;
  }
}

// 减少兑换数量
function decreaseQuantity() {
  if (exchangeQuantity.value > 1) {
    exchangeQuantity.value--;
  }
}
</script>

<style>
.product-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.product-swiper {
  width: 100%;
  height: 750rpx;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

.product-info {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.price-section {
  margin-bottom: 20rpx;
}

.points-price {
  font-size: 40rpx;
  color: #ff6b6b;
  font-weight: bold;
  margin-right: 20rpx;
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
}

.title-section {
  margin-top: 20rpx;
}

.product-name {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.product-tags {
  display: flex;
  gap: 20rpx;
}

.detail-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 30rpx;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #ff6b6b;
  border-radius: 3rpx;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.detail-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-size: 28rpx;
}

.value {
  color: #333;
  font-size: 28rpx;
}

.description-section {
  background-color: #fff;
  padding: 30rpx;
}

.description-content {
  color: #666;
  font-size: 28rpx;
  line-height: 1.6;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity-section {
  display: flex;
  align-items: center;
}

.quantity-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #ff6b6b;
  color: #fff;
  font-size: 28rpx;
  border: none;
  border-radius: 50%;
  margin: 0 5rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-btn:active {
  opacity: 0.8;
}

.quantity-btn[disabled] {
  background-color: #ccc;
  opacity: 0.5;
}

.quantity-value {
  font-size: 28rpx;
  color: #333;
  margin: 0 10rpx;
  min-width: 40rpx;
  text-align: center;
}

.exchange-btn {
  width: 60%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #ff6b6b;
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
  border: none;
}

.exchange-btn:active {
  opacity: 0.8;
}

.category-tag, .status-tag {
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.user-points-section {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-points-label {
  font-size: 28rpx;
  color: #666;
}

.user-points-value {
  font-size: 32rpx;
  color: #ff6b6b;
  font-weight: bold;
}
</style>
